# _*_ encoding: utf-8 _*_
# __author__ = 'lx'
from spider import config
from spider.ytb_v3_api.ytb_manager import YoutubeManager

manager = YoutubeManager()

class YoutubeAPI:
    def __init__(self, api_key):
        manager.set_api_key(api_key)
        self.parts = ['id', 'snippet']

    def get_api_key(self):
        return manager.get_api_key()

    def change_api_key(self, api_key):
        return manager.set_api_key(api_key)

    def get_video_info(self, video_id):
        api_url = manager.get_api('videos')
        params = {
            'id': video_id,
            'part': 'id, snippet, contentDetails, player, statistics, status'
        }

        video = manager.api_request(api_url, params)
        return video

    # 通用搜索
    # param     keyword     关键词
    # param     max_results 结果数量 可接受值为1到100
    # param     pageToken   下一页标识
    def general_search(self, keyword, max_results=10, pageToken=None):
        api_url = manager.get_api('search')
        params = {
            'q': keyword,
            'part': 'id, snippet',
            'maxResults': max_results
        }

        if pageToken:
            params['pageToken'] = pageToken

        objects = manager.api_request(api_url, params)
        return objects

    def video_search(self, keyword, max_results=10, order=None, pageToken=None, parts=None):
        api_url = manager.get_api('search')
        if parts is not None:
            invalid_parts = [x for x in parts.split(',') if not x.strip() in self.parts]
            if len(invalid_parts) > 0:
                raise ValueError('Invalid Part Used: ' + ','.join(invalid_parts))
        else:
            parts = 'id, snippet'
        params = {
            'q': keyword,
            'type': 'video',
            'part': parts,
            'maxResults': max_results
        }
        if order:
            params['order'] = order

        if pageToken:
            params['pageToken'] = pageToken

        videos = manager.api_request(api_url, params)
        return videos

    def video_search_in_channel(self, keyword, channel_id, max_results=10, order=None, pageToken=None):
        api_url = manager.get_api('search')
        params = {
            'q': keyword,
            'type': 'video',
            'channelId': channel_id,
            'part': 'id, snippet',
            'maxResults': max_results
        }

        if order:
            params['order'] = order

        if pageToken:
            params['pageToken'] = pageToken

        videos = manager.api_request(api_url, params)
        return videos

    def get_channel_by_name(self, channel_name):
        api_url = manager.get_api('channels')
        params = {
            'forUsername': channel_name,
            'part': 'id,snippet,contentDetails,statistics,invideoPromotion'
        }

        channel = manager.api_request(api_url, params)
        return channel

    def get_channel_by_id(self, channel_id):
        api_url = manager.get_api('channels')
        params = {
            'id': channel_id,
            'part': 'id,snippet,contentDetails,statistics,invideoPromotion'
        }

        channel = manager.api_request(api_url, params)
        return channel

    def get_playlist_by_id(self, playlist_id):
        api_url = manager.get_api('playlists')
        params = {
            'id': playlist_id,
            'part': 'id, snippet, status'
        }

        playlist = manager.api_request(api_url, params)
        return playlist

    def get_playlist_by_channel_id(self, channel_id):
        api_url = manager.get_api('playlists')
        params = {
            'channelId': channel_id,
            'part': 'id, snippet, status'
        }

        playlist = manager.api_request(api_url, params)
        return playlist

    # 通过播放列表id获取播放列表
    def get_playlist_items_by_playlist_id(self, playlist_id, max_results=50, pageToken=None):
        api_url = manager.get_api('playlistItems')
        params = {
            'playlistId': playlist_id,
            'part': 'id, snippet, contentDetails, status',
            'maxResults': max_results
        }

        if pageToken:
            params['pageToken'] = pageToken

        playlist_items = manager.api_request(api_url, params)
        return playlist_items

    # 通过视频id获取评论线
    # param     video_id        视频id
    # param     part            设定返回包含的资源'id,replies,snippet'
    # param     max_results     设定返回结果数
    # param     order           设定排序'time' or 'relevance'
    # param     pageToken       下一页标识
    # param     searchTerms     按措辞搜索(模糊匹配)
    def get_comment_threads_by_video_id(self, video_id, part='replies,snippet', max_results=20, order='time',
                                        pageToken=None, searchTerms=None):
        api_url = manager.get_api('commentThreads')
        params = {
            'videoId': video_id,
            'part': part,
            'maxResults': max_results,
            'order': order,
        }

        if pageToken:
            params['pageToken'] = pageToken
        if searchTerms:
            params['searchTerms'] = searchTerms

        comments = manager.api_request(api_url, params)
        return comments

    async def get_comment_threads_by_video_id_async(self, video_id, part='replies,snippet', max_results=20, order='time',
                                        pageToken=None, searchTerms=None):
        api_url = manager.get_api('commentThreads')
        params = {
            'videoId': video_id,
            'part': part,
            'maxResults': max_results,
            'order': order,
        }

        if pageToken:
            params['pageToken'] = pageToken
        if searchTerms:
            params['searchTerms'] = searchTerms

        comments = await manager.async_request(api_url, params)
        return comments


if __name__ == '__main__':
    api = YoutubeAPI(config.GOOGLE_APIKEY)
    # video = api.get_video_info('lRtedsK_6fs')
    # results = api.general_search('杨永信', max_results=10)
    # videos = api.video_search('邪教惩罚性学校', max_results=10, order=None)
    # videos2 = api.video_search_in_channel('美国版"杨永信"邪教惩罚性学校', 'UCaSlyjhR4WC7QhYuaivxb6g', max_results=10, order=None)
    #
    # channel = api.get_channel_by_name('Nathan Rich')
    # channel2 = api.get_channel_by_id('UCaSlyjhR4WC7QhYuaivxb6g')
    #
    # playlist = api.get_playlist_by_id('PLo4_KHAgJYFy8aLGOIpmmM8410Kz2kZlg')
    # playlist2 = api.get_playlist_by_channel_id('UCaSlyjhR4WC7QhYuaivxb6g')
    #
    # playlistItems = api.get_playlist_items_by_playlist_id('PLo4_KHAgJYFy8aLGOIpmmM8410Kz2kZlg', max_results=20)
    comments = api.get_comment_threads_by_video_id('OSX3ik9Z4X8')

    print(comments)
